<?php
/**
 * Controller to manage categories assigned to product in admin area
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 * 
 */
class admin_Product2categoryController extends Bel_Controller_Aed  {

	/**
	 * Initialization. Creates left menu for index & form action
	 * Redifines _form_action, _index_action and _delete_action URLs by adding 
	 * product_id param
	 * 
	 */
	function init() {
		$this->_model = new Models_Products_Categories();
		$this->_model->setProduct($this->_request->getParam('product_id'));
		$this->_formname = 'product_categories_form';
		parent::init ();
	
		if($this->_request->getParam('product_id') && ($this->_request->getActionName()=='index'||$this->_request->getActionName()=='form')){
			Helpers_Products_Admin_ProductsMenu::leftMenu($this->_request->getParam('product_id'));
		}	

		$this->_form_action = $this->_form_action.'/product_id/'.$this->_request->getParam('product_id');
		$this->_index_action = $this->_index_action.'/product_id/'.$this->_request->getParam('product_id');		
		$this->_delete_action = $this->_delete_action.'/product_id/'.$this->_request->getParam('product_id');
	}
	
	/**
	 * Clears product cache after modify action
	 *
	 */
	protected function _afterModify(){
		Helpers_Products_Cache::clearProductCache($this->_request->getParam('product_id'));
	}
	
	/**
	 * Clears product cache after delete action
	 *
	 */
	protected function _afterDelete(){
		$this->_afterModify();
	}	
	
	/**
	 * Populates categories dropdown of form with categories options 
	 *
	 * @param Bel_Forms_Builder $form
	 */
	protected function _prepareForm(Bel_Forms_Builder $form){
		$oCategories = new Models_ProductCategories();
		$categories = $oCategories->getTree('category_level>1');
		
		if(count($categories)){
			$options = array();
			
			foreach ($categories as $category){
				$options[$category->category_id] = str_repeat('&nbsp;', 2*($category->category_level-2)).$category->category_name;	
			}
			$form->addSubElement('category_id','options',$options);
			$form->addAttributes('product_id',array('value'=>$this->_request->getParam('product_id')));
		}else{
			$this->_messages->setMessage('Categories not exixst. Add few first!', 'error');
			$this->_redirect($this->_index_action);
		}
	}
}